Write-Output 'loading functions!'
'-----------------add function below-----------'

function remove_colors_icons
{
    param (
    )
    # keep the icons but remove colors except black texts
    <# PS C:\Users\cxxu\Downloads\Compressed> h terminal-icons

Name                              Category  Module                    Synopsis
----                              --------  ------                    --------
Set-TerminalIconsTheme            Function  Terminal-Icons            Set the Terminal-Icons color or icon theme
Set-TerminalIconsIcon             Function  Terminal-Icons            Set a specific icon in the current Terminal-Icons icon theme or allows…
 #>
    Set-TerminalIconsTheme -DisableColorTheme
    # Remove-Module Terminal-Icons 

}
function ps_group
{
    Get-Process | Group-Object ProcessName | Sort-Object Name
}
function tomcat_restart
{
    tomcatshutdown
    tomcat
}
function navicat
{
    navicat_exe
}
function navicat_reset_try
{
    Invoke-Expression "$scripts\software_crack_scripts\reset_navicat_try.bat"
}
function pg
{
    Import-Module posh-git
    i2_cxxu
}
function rpg
{
    Remove-Module posh-git
    Remove-Module oh-my-posh  
}

function ord
{

    param(
        $char
    )
    [byte][char]"$char"
}
function chr
{
    param(
        $ascii_value = 0
    )
    [char][int]"$ascii_value"
}
function gitbook
{
    ELA
    Set-Location docs/00_课堂文档
    py -m http.server

}
function upload_pubKey
{
    param(
        $source = "$env:sshPub"
        , 
        $user_host = "cxxu@$AlicloudServerIp"
        ,
        $target = '~/.ssh/authorized_keys'
    )
    scp $source "$user_host`:$target"
}

function BT
{
    Start-Process http://123.56.72.67:8888/d97fbc20
}
function headPwsh
{
    param (

        $file,
        $number = 10
    )
    
    Get-Content $file -head $number | ForEach-Object { '{0,-5} {1}' -f $_.ReadCount, $_ }
}
function tailPwsh
{
    param (
        $file,
        $number = 10
    )
    # catn $file | Select-Object -Last $number
    Get-Content $file -head $number | ForEach-Object { '{0,-5} {1}' -f $_.ReadCount, $_ }
    
}
function colorPicker_vscode
{
    c $env:blogs\styles\colorPicker.css 
}
function updatePowershell_msi
{
    param (
    )
    Write-Output '@maybe you need to try severial times!...'
    Invoke-Expression "& { $(Invoke-RestMethod https://aka.ms/install-powershell.ps1) } -UseMSI"
}
function scp_to_host
{
    param(
        $source_opt = 'D:\repos\scripts\linuxShellScripts',
        $user_host = 'cxxu@u20',
        $target_path = '~'
    )
    scp -r $source_opt $user_host`:$target_path
}
function scp_to_ali
{
    <# 
    .Example
    scp_to_Ali .\pets.txt ~
    _____
    PS D:\repos\blogs\linuxCommandsTutor> scp_to_Ali .\pets.txt ~
    cxxu@12x.xx.x.7's password:
    pets.txt
    #>
    param (
        $source,
        $targetPath_opt = '~',
        $options_opt = '-r'
    )
    scp $options_opt $source "$cxxuAli`:$targetPath_opt" 
}
function scp_from_ali

{
    param(
        $from_user_hostname = "cxxu@$AliCloudServerIP",
        $source = '~/linuxShellScripts',
        $target = $env:desktop

    )
    # 可以不用引号/加号,直接拼接变量为字符串!
    scp -r $from_user_hostname`:$source $target
}
function mysqlRootLocal
{
    $cli = "mysql $mysqlPrompt -u root -p1"
    Invoke-Expression $cli

}
function mysqlLocal
{
    param (
        $userName
    )
    $cli = " mysql $mysqlPrompt -u $userName -p1"
    Invoke-Expression $cli
}
function mysqlRemote
{
    param (
        $userName,
        $p = '1'
    )
    $cli = "mysql $mysqlPrompt -u $userName -p$p"
    Invoke-Expression $cli
}
function mysqlCxxuAli
{
    $cli = " mysql $mysqlPrompt -u cxxu -h $AliCloudServerIP -p1"
    Invoke-Expression $cli
}
function mysqlRootAli
{
    param (
    )
    $cli = "  mysql $mysqlPrompt -u root -h $AliCloudServerIP -p1"
    Invoke-Expression $cli

}
function getAssembler_att
{
    param(
        $fileName
    )
    g++ -S $fileName 
}
function getAssemble_intel
{
    param(
        $fileName
    )
    g++ -S -masm=intel $fileName -o "$($fileName)_intel"       
}
function CxxuAli { ssh cxxu@$AliCloudServerIP }
function rootAli { ssh root@$AliCloudServerIP }
# function catn
# {
#     <# 
#     .Synopsis
#     Mimic Unic / Linux tool nl number lines
   
#     .Description
#     Print file content with numbered lines no original nl options supported
   
#     .Example
#      nl .\food.txt
#     #>
#     param (
#         [parameter(mandatory = $true, Position = 0)]
#         [String]$FileName
#     )

#     process
#     {
#         If (Test-Path $FileName)
#         {
#             # core logic for the function
#             # 关键在于格式化'{0,5} {1}' -f
#             Get-Content $FileName | ForEach-Object { '{0,-5} {1}' -f $_.ReadCount, $_ }
#         }
#     }
# }
function tree_lsd
{
    param(
        $depth_opt = 3
    )
    lsd --tree --depth $depth_opt
}
function ld
{
    lsd -l --color never
}
function l1
{
    lsd -1
}

function envAdder
{
    <# 
    .synopsis
    add a value to a specified environment variable
    often, the most  useful variable is `Path`;
    and the most often operation is add value to the Path 
    ;
    if the target value is no exist yet, then the function will try to create the corresponding variable for you!
    本函数既可以为已有的环境变量添加新值,也可以增加一对全新啊的变量=值对;
    但此时这里会前置一个分号(不影响使用),如果有需要清除,可以稍微加一个判断在函数里来完善逻辑
    .example
    envAdder -target_env path -new_value tester1112
    #>
    param(
        $target_env = 'path',
        $new_value,
        $scope_opt = 'Machine'
    )
    # 检测当前是具有管理员权限,如果没有,要求用户使用管理员方式打开,(随之抛出一个错误!)
    isAdministratorPrivilege
    #精心调试过
    $updated_value = "$(Invoke-Expression("`$env:$target_env"));" + "$new_value"
    # $update_value -split ';'#可以用来分行查看结果
    # Write-Output $updated_value
    [Environment]::SetEnvironmentVariable( $target_env, $updated_value, $scope_opt)
}
function remote_folder
{
    param(
        $hostname_opt = "$AliCloudServerIP",
        $dir = '/home/cxxu/cppCodes'
    )
    code --folder-uri "vscode-remote://ssh-remote+$hostname_opt$dir"
}
function catn
{
    <# 
    .Synopsis
    Mimic Unic / Linux tool nl number lines
   
    .Description
    Print file content with numbered lines no original nl options supported
   
    .Example
     nl .\food.txt
    #>
    param (
        $Path = '',
        [Parameter(ValueFromPipeline)]
        [String]
        $content
        # $FileName
 
    )
    begin
    {
        $i = 0;
    }    process
    {

        if ($path -eq '')
        {
            $content | ForEach-Object {
                $i++;
                '{0,-5} {1} ' -f $i, $_ ;
            
            }
        }
        else
        {
            # $content = (Get-Content $Path)
            Get-Content $Path | ForEach-Object {
                $i++;
                '{0,-5} {1} ' -f $i, $_ ;
            
            }
        }
    }
}
function stopByName
{
    param(
        $ProcessName
    )
    Stop-Process -Verbose -Name $ProcessName
}
function openAll
{
    <# 
    .synopsis
    open all file that exist in the current directory with default program 
    #>
    # --------------
    <#     if (Test-Path ./openAllFiles.ps1)
    {
        Remove-Item openAllFiles.ps1 -V
    }
    Get-ChildItem -File | ForEach-Object { ".`/" + $_.Name>>openAllFiles.ps1 }
    ./openAllFiles.ps1
    Write-Output 'end the openAll script running'
    # 删除临时脚本:
    Remove-Item ./openAllFiles.ps1 #>

    # ----------------------

    Get-ChildItem -File | ForEach-Object { Write-Output $_; & $_ }
}
function openPatternXFiles
{
    <# 
    .synopsis
    default:open all file that exist in the current directory with default program 
    #>
    param(
        $pattern = '*'
    )
    Get-ChildItem -File $pattern | ForEach-Object { Write-Output $_; & $_ }
}
function gitconfigEdit
{
    c $env:userProfile\.gitconfig
}
function getPath
{
    param(
        $pattern
    )
    $pattern = "*$pattern*"
    Get-Process $pattern | Select-Object Name, path
}
function scoopInstall
{
    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
    # or shorter

    Invoke-WebRequest -useb get.scoop.sh | Invoke-Expression
    Write-Output 'if failed ,please try the proxy to reconnect the https://get.scoop'
}
function drivers_diskInfo
{
    Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Name.Length -eq 1 }
    Write-Output '😊❤️only show the disk with the name that no more than 2 characters'
}
function showSrcCode
{
    param(
        # [parameter(Mandatory = $true)]
        [Parameter(ValueFromPipeline = $true)]
        # [scriptblock] $command
        $command
    )
    Get-Command $command | Select-Object -ExpandProperty ScriptBlock
}
function  dj_start_proj
{
    param (
    )
    django-admin.exe startproject $1 $2
    Write-Output $args
}
function prepareSymbolVscodeHome
{
    Write-Output 'try to new-item junction...'
    newJunction $env:vscode_Home $env:vscode_home_D 
}

function newHardLink
{
    param(
        $Path = 'slides.md',
        [String]$target 
    )
    # 下面这段判断处理可有可无
    <# if ($target.ToString().StartsWith(".\")) {
        $target=$target.TrimStart(".\")
    } #>
    # $absTarget = "$pwd\" + "$target"
    $absTarget = (Get-ChildItem $target).FullName
    Write-Output "$absTarget will be target!"
    # $absTarget = Invoke-Expression $absTarget
    Write-Output "@$absTarget"
    # $absTarget = $pwdPrefix + $target
    Write-Output '@注意,Target必须使用绝对路径!'
    Write-Output "@当然, 也可以是这样的表达式:`"`$pwd\\file`""
    Write-Output '@带上-target 选项'
    if (Test-Path $Path)
    {
        rmFV $Path
    }
    New-Item -ItemType HardLink -Path $Path -Target $absTarget -Force -Verbose
}
# newHardLink
function slidesRefactor
{
    param(
        $Target
    )
    newHardLink -target $Target
}

function newJunction
{
    param(
        $Path,
        $Target,
        $IsSudo = ''
    )
    Write-Output 'if failed(access Denied), please run the terminal with administor permission.(考虑到部署的门槛，scoope未必可用，您需要手动打开带有管理员权限的terminal进行操作（而不在这里使用sudo;这里提供了参数，您可以传入sudo选项）'
    if (Test-Path $path)
    {
        Remove-Item -Force -Verbose $path 
        Write-Output 'removing the existing dir/symbolicLink!'
        countdown_timer;
    }
    if ($IsSudo -eq '')
    {

        New-Item -Verbose -Force -ItemType junction -Path $Path -Target (getAbsolutePath $Target)
    }
    else
    {
        sudo New-Item -Verbose -Force -ItemType junction -Path $Path -Target $Target
    }
}
function batteryChargePer
{
    # get battery charge:
    $charge = Get-CimInstance -ClassName Win32_Battery | Select-Object -ExpandProperty EstimatedChargeRemaining
    "Current Charge: $charge %."
}
function u20
{
    ssh cxxu@u20
}
function backupCppVscode
{
    cpFVR $env:repos\cpp\acmconsoleapps\.vscode $env:configs\CppVscodeConfig
}
function deployPython
{
    newjunction -path $env:APPDATA\python -target $env:pythonPacks_Home_Conv
}
function deployCppVscodeThere
{
    param(
        $path = '.vscode'
    )
    if (!(Test-Path '.vscode'))
    {
        # Get-ChildItem $env:configs\CppVscodeConfig\
        mkdir .vscode
        
    }
    cpFVR $env:configs\CppVscodeConfig\* .vscode
    PrintBorder
    Write-Output "@path=$path"

}
function backupPicgoConfig
{
    param (
        
    )
    Write-Output 'for CLI part'
    cpFVR $env:picgo_CLI_config\*.json $env:configs\PicgoConfigs
    Write-Output 'for GUI part'
    cpFVR $env:picGo_Conf\data.json $env:configs\PicgoConfigs
}
function deployPicgoConfig
{
    Write-Output 'for CLI part'
    cpFVR $env:configs\PicgoConfigs\* $env:picgo_CLI_config
    Write-Output 'for GUI part'
    cpFVR $env:configs\PicgoConfigs\* $env:picgo_conf
}
function deployPicgoGUI
{
    cpFVR
}
function deployAndroidStudio_depends
{
    param (
        
    )
    Write-Output "gradle_user_home `\n; androidDepends"
    # if (Test-Path $env:androidDepends)
}

function vscodeExtListExport
{
    param(
        $fileName = "vscode_list_extt$(Get-Date)"
    )
    code --list-extensions >> $fileName
}
function deployWinxRay
{
    param (
        
    )
    newJunction $env:winxrayConf $env:configs\proxyToolsConfigs\winxrayRules
}
function deployTypora
{
    junction -path $env:APPDATA\Typora $env:configs\Typora
    # cpFVR $env:configs\typora\themes $env:APPDATA\Typora\
    # cpFVR $env:configs\typora\conf $env:APPDATA\Typora\
    Write-Output "the basic settings need you to manually set(the config.json just provide the advanced part settings
        `n the themes settings need you to chose manually , too; It will be provide in the appearance->themes dropdown
        `n just set the preference->markdown->math formula checkboxes!
        `n after that , restart the typora to apply the settings!"
}
function backupTyporaConf
{
    Write-Output 'deprecated! please considering the symlink!'
    # cpFVR $env:APPDATA\Typora\themes $env:configs\Typora\Themes
    # cpFVR $env:APPDATA\Typora\conf $env:configs\Typora\conf
}
function git_clone_shallow
{
    param (

        $gitUrl
    )
    Write-Output "clone with `n @--depth 1 `n --fileter=blob:none `n $gitUrl"
    git clone --depth 1 --filter=blob:none $gitUrl
}
function gitUpdateReposSimply
{
    param (
        $comment = "general update project $(Get-Date)",
        $branch = 'main'
    )
    git add .
    git commit -m $comment
    git push origin $branch
    PrintBorder '😎'
    git status
    PrintBorder '>'
    Write-Output "@comment=`"$comment`""
    Write-Output "@branch=$branch"  
}
function git_proxy_set
{
    <# 
    .synopsis
    打开或者关闭gitconfig的全局配置;操作完成后查看配置文件
    .example
     git_proxy_set -switch_opt off
    .example
     git_proxy_set -switch_opt on
    .example
    git_proxy_set -switch_opt on -port_opt 1099
    #>
    param(
        $switch_opt = 'on',
        $port_opt = '10801',
        $localhost_opt = 'http://127.0.0.1'

    )
    $localhost = $localhost_opt
    $socket = "$localhost`:$port_opt"
    if ($switch_opt -eq 'on')
    {

        git config --global http.proxy $socket
        git config --global https.proxy $socket
    }
    elseif ($switch_opt -eq 'off')
    {   
        git config --global --unset http.proxy
        git config --global --unset https.proxy
    }
    
    bat $home/.gitconfig

}
function https
{
    param(
        $domain
    )
    Start-Process $domain
}
function httpsw
{
    param (
        $domain
    )
    $url = "www.$domain"
    Start-Process $url
    Write-Output "try to open https url:🎶 $url"
}

function cxxuAli_update_alias_envs_vimrc
{
    $pwdir = Get-Location
    linuxShellScripts_
    scp_to_Ali -source .\envs.sh -targetPath_opt ~/linuxShellScripts
    scp_to_Ali -source .\alias*.sh -targetPath_opt ~/linuxShellScripts       
    
    scp_to_Ali -source .\.zshrc -targetPath_opt ~
    scp_to_Ali -source .\.vimrc -targetPath_opt ~
    Set-Location $pwdir
    
}
function startapp
{
    param(
        $name
    )
    django-admin.exe startapp $name
}
function pmg
{
    param(
        $cmd = '',
        $p1 = '',
        $p2 = '',
        $p3 = '',
        $p4 = ''

    )
    py manage.py $cmd $p1 $p2 $p3 $p4 
}
function sqlmigrate
{
    param(
        $appName,
        $migration
    )
    pmg sqlmigrate $appName $migration
}
function showmigrations
{
    param(
        $parameter = ''
    )
    pmg showmigrations $parameter
}
function pmgmk
{
    param (
        $parameter = ''
    )
    pmg makemigrations $parameter
    
}
function pmgmi
{
    param (
        $parameter
    )
    pmg migrate $parameter
}

function Django_env_Home
{
    param (
        
    )
    Set-Location D:\repos\PythonLearn\Django_env
}
function runserver_jango
{
    if (Test-Path 'manage.py')
    {
        
        py manage.py runserver
    }
    else
    {
        Write-Output 'please set-location correctly!'
    }
}
function ela_startup
{
    env_django4
    Write-Output 'venv started done!'
    Set-Location D:\repos\ELA\backEnd
    pmg runserver 8000
}
function env_django4
{
    param(
        $switch_opt = 'on'
    )
    # Invoke-Expression "$ll_env\scripts\activate"
    # Set-Location $ll_env\scripts
    Set-Location "$DjangoVenvs\django4\scripts"
    if ($switch_opt -eq 'on')
    {
        Get-Location
        Write-Output 'try to active the django4 environment...'
        ./activate
        Write-Output 'done!'
    }
    else
    {
        'try to deactivate the env!'
        # ./deactivate
        deactivate
        'done!'
    }
    Set-Location -  
    # 激活虚拟环境需要到虚拟环境所在根目录下执行,故而先做目录切换
    # ./activate

}
function env_django2
{
    <# 
    .synopsis
    不切换目录的情况下,快捷开关虚拟环境
    以下代码针对于我本地的django2虚拟环境
    .example
     env_django2 -switch_opt on
    #>
    param(
        $venvPath_opt = "$env:pyEnvs\Django2\scripts",
        $switch_opt = 'on'
    )
    # 必须在虚拟环境目录下激活才能达到目的(简单设置active文件的别名将会闪退)
    Set-Location $venvPath_opt
    if ($switch_opt -eq 'on')
    {
        ./activate
    }
    else
    {
        'try to deactivate the env!'
        deactivate
        'done!'
    }
    # 进入到active所在目录,才可以正确在当前终端正确激活/关闭虚拟环境
    # 激活/关闭虚拟环境后,返回到原来的工作目录中.
    Set-Location -
}

# if ( ( Get-Location | Resolve-Path).ToString() -eq "django" )
function hibernate
{
    param (
        
    )
    shutdown /h
}
function shutdown_now
{
    Write-Output 'the pc will be shutdown '
    # in 3 senconds'
    # Write-Output '❤️⛔control+c to stop the behaviour...'
    # countdown_timer 3
    $Inquery = Read-Host -Prompt ' input y key to continue shutdown!(prevent the unexpected shutdown) '
    if ($Inquery -eq 'y')
    {
        shutdown /p
    }
}
function reboot
{
    param(
        $timeOut = 0
    )
    shutdown /r -t $timeOut
}
function cpFV
{
    param(
        $src,
        $des
    )
    Copy-Item -Force -Verbose $src $des
}
function cpFVR
{
    param(
        $src,
        $des
    )
    Copy-Item -Force -Verbose -Recurse $src $des
}
function backupVsCodeSettings
{
    cpFV $env:vscodeConfHome\*.json $env:configs\vscodeSettings
    cpFVR $env:vscodeConfHome\snippets $env:configs\vscodeSettings
}
function BackupGitConfig
{
    cpFVR $env:userProfile\.gitconfig $env:configs
}
function deployGitConfig
{
    <# 
    .synopsis it is so shame that the hardlink could not be created between two different disk drive.
    #>
    # $gitconfig_path="$profile\.gitconfig"
    # if(test-Path $gitconfig_path ){
    #     rename  $gitconfig_path '.gitconfig.bak'
    #     echo "backup done!"
    # }
    hardlink -path $gitconfig_path -target $env:configs\.gitconfig
    cpFVR $env:configs\.gitconfig $env:USERPROFILE
}
function countdown_timer
{
    param(

        $i = 5
    )
    while ($i--)
    {
        Start-Sleep -Seconds 1
        Write-Output ($i + 1);

    }
}
function isAdministratorPrivilege
{
    if (!([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544'))
    {

        Write-Output '🤣😂😊current powershell run without administrator privilege!;请手动打开管理模式的terminal.'
        return
    }
}

function deployVsCodeSettings_depends
{
    <# redifine the extensions path to D district #>
    if (!([Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544'))
    {

        Write-Output 'current powershell run without administrator privilege!;请手动打开管理模式的terminal.'
        return
    }
    if (Test-Path $env:vscode_Depends)
    {
        Write-Output 'you run the script after vscode have been installed!,this will remote the old home to create the coresponding symbolic link!'
        Remove-Item $env:vscode_Depends
    }
    Write-Output 'pre-set the directory as a symbolic link to D partition.. '
    Write-Output 'sleep for 3 senconds for you to think of it whether to stop...'
    # when you debug,you can set the time longer(such as 10 seconds)
    countdown 10;
    Write-Output "repointer the software location:$env:vscode_home->$env:vscode_Home_D "
    newJunction $env:vscode_home $env:vscode_Home_D
    # assure the newJunction could run successfully
    Write-Output "newJunction $env:vscode_Depends $env:vscode_Depends_D"
    if (
        !(Test-Path $env:vscode_Depends_D)
    )
    {
        # 读取键盘输入(read input by read-host)
        $Inquery = Read-Host -Prompt "there is not $env:vscode_Depends_D ; to create the corresponding directory, enter 'y' to continue😎('N' to exit the process!)  "
        if ($Inquery -eq 'y')
        {
            mkdir $env:vscode_Depends_D;
        }
        else
        {
            return;
        }
    }
        
    newJunction $env:vscode_Depends $env:vscode_Depends_D
    #deploy the settings
    cpFVR $env:configs\vscodeSettings\* $env:vscodeConfHome
}

function backupWtSettings
{
    cpFV $env:wtConfSettings\settings.json $env:repos\configs\wtConfSettings.json
}
function deployWtSettings
{
    cpFV $env:configs\wtConfSettings.json $env:wtConfSettings\settings.json
}
function backupPwshProfile
{
    Copy-Item -Force -Verbose $profile.AllUsersAllHosts $env:repos\configs
}
function deployPwshProflie
{
    <# 这个函数要用环境变量,要使用相对路径,保证可用性! #>
    $Inquery = Read-Host -Prompt "this command will overwrite the $profile.alluserallhost file, enter 'y' to continue😎 "
    if ($Inquery -eq 'y')
    {
        Write-Output '如果不成功,请使用管理员模式进入powershell'
        # $cf_profile_version = "$env:repos\configs\profile.ps1"
        $script_profile_version = "$env:scripts\modulesbycxxu\.profileAll.ps1"
        sudo Copy-Item -Verbose -Force $script_profile_version $profile.AllUsersAllHosts 
    }
    else
    {
        Write-Output 'operation canceled!'
    }
}
function hosts
{
    Write-Output 'entering administrator mode...'
    Write-Output 'try to open hosts file(by vscode...)'
    # sudo_pwsh
    sudo c $env:hosts
}
function galD
{
    param(
        $Cmdlet
    )
    Get-Alias -Definition $Cmdlet
    
}
function pingBD
{
    param (

        $site = 'www.baidu.com'
    )
    ping $site
}
function pingGG
{
    param (
        $domain = 'www.google.com'
    )
    Write-Output $domain
    ping $domain
}
function uploadPic
{
    param (
        $path = ' '
    )
    if ($path -eq ' ')
    {
        Write-Output 'try to upload pictures from clipboard(the default behaviour)'
    }
    $resLink = picgo upload $path | Select-Object -Last 1 
    Set-Clipboard $resLink
    Write-Output "🎶🎶🎶`n$resLink"
}
function uploadPicMarkdown
{
    param (
        $path = ' '
    )
    if ($path -eq ' ')
    {
        Write-Output 'try to upload pictures from clipboard(the default behaviour)'
    }
    $resLink = picgo upload $path | Select-Object -Last 1 
    # Set-Clipboard $resLink
    $markdownPicLink = "![🥰$(Get-Date)]($resLink)"
    Write-Output $markdownPicLink
    Set-Clipboard $markdownPicLink
    Write-Output "🎶🎶🎶`n$resLink"
}
function PrintBorder
{
    param (
        $borderUnit = '-~',
        $timesOfRepeat = 30
    )
    # $border = ''
    $border = $borderUnit * $timesOfRepeat
    <#     # Write-Output 50*$borderUnit
    # for ($i = 0; $i -lt $timesOfRepeat; $i++)
    # {
    #     # $border = $border + $borderUnit
    #     $border += $borderUnit
    # } #>
    # Write-Output $border
    # return语句也会自动打印出来
    return $border
}
#----------------------------
# PrintBorder > 5
function gcmw
{
    param (
        $pattern
    )
    $wildcardPattern = "*$pattern*"
    Write-Output "🥰result returned by gcm wildcard:$wildcardPattern"
    PrintBorder
    Get-Command $wildcardPattern
    # Write-Output "🥰result returned by help"
    PrintBorder
    # Get-Help $wildcardPattern
    # help $Pattern |Format-Table |Write-Output

}
# gcmw screen
function mvToNEEPSub
{
    param (
        $obj,
        $desBase
    )
    $des = "$env:Neep`\$desBase"

    Move-Item $obj $des
    Write-Output "displayed:$des = $env:Neep`\$desBase"
}
function clock
{
    node $env:scripts\jsScripts\clock.js
}
function javav
{
    java -version
}
function gitLogGraphSingleLine
{
    #is there a decorate option seems does not matter.
    git log --all --decorate --oneline --graph
}
function mvExcludeFolder
{
    <# 
    .Example
    ls *pic* |foreach {if ($_.Name -ne "picturebeds") {mv -v $_ .\pictureBeds\ }}
     #>
    param(
        $pattern,
        $target_excludeDir
    )
    Get-ChildItem $pattern -Exclude $target_excludeDir | Move-Item -Verbose -Destination $target_excludeDir
    # | ForEach-Object { if ($_.Name -ne $target_excludeDir) { Move-Item -v $_ $target_excludeDir } }
}
function gitLogGraphDetail
{
    git log --graph --all
}
function EnvironmentRequireTips
{
    Write-Output "💕you are try to run the python script; `n 💕if it does not work, please check the py command to check the python enviroment to locate the exceptions."
}
function wifi_wlan_connect
{
    param(
        $ssid = 'ZJGSU-Student'
    )
    Write-Output "try connecting to wifi ssid:$ssid"
    netsh wlan connect name=$ssid
}
function renamePrefix
{
    param (
        $dirName
    )
    EnvironmentRequireTips;
    py $env:scripts\pythonScripts\rename_prefix.py $dirName
}
function searchFiles
{
    <# 
    .synopsis
    从当前目录开始递归查找具有指定名称的文件
    #todo 函数当前存在问题!!!!!!!!!!!
    .Example 
    searchFiles "css" 
    #>
    param(
        $pattern,
        $path_opt = './',
        $isWildcard = 'y'
    )
    if ($isWildcard -eq 'y')
    {
        $pattern = "*$pattern*"
    }
    printWorkingDir $path_opt
    # $wildPattern="*$pattern*"
    Get-ChildItem -File  $pattern -R | Get-ChildItem -Exclude '*node_modules*' | Select-Object FullName
    # ls -file -r $pattern
    # ls -file index.html -R|select FullName 
}

function listRecurse
{
    param(
        $path = 'd:/repos/blogs/neep'
    )
    $lst = (Get-ChildItem -Directory $path)
    $len = $lst.Length
    while ($len)
    {
        $lst | ForEach-Object {
            
            listRecurse $_
        } 
    }
}
function typoraConfEdit
{
    c $typoraConfig\conf.user.json
}
function searchContentWithSpecifiedFiles
{
    <# 
    .synopsis
    search file which contain given keyword or content
    default with wildcard `*`
    the function will track the symbolink!

    #>
    param(
        $content,
        $fileNamePattern_opt = '*',
        $dirFrom_opt = '.'
    )
    printWorkingDir $dirFrom_opt
    # Get-ChildItem -Path $dirFrom -File -Filter $fileNamePattern -Recurse | Select-Object FullName | ForEach-Object { Select-String -Path $_.FullName -SimpleMatch      -Pattern  "$content" }
    Get-ChildItem -Path $dirFrom_opt -File $fileNamePattern_opt -Recurse -FollowSymlink | ForEach-Object { Select-String -Path $_.FullName -SimpleMatch -Pattern "$content" }

    # Write-Output $PSBoundParameters
    PrintBorder

    Write-Output "@content=$content,
        `n@fileNamePattern=$fileNamePattern_opt,
        `n@DirFrom=$(Resolve-Path $dirFrom_opt)
        "
    # PrintBorder
    # Get-ChildItem -Path $dirFrom -File -Filter $fileNamePattern -Recurse 
}
function searchConstStrWithCatn
{
    param (
        $pattern,
        $path = '.'
    )
    printWorkingDir "$path"
    PrintBorder
    # todo
    # Get-ChildItem $env:scripts\ModulesByCxxu\ConstantStrings -r | ForEach-Object { if ($_.ToString() -like "* $pattern * ") { Write-Output $_ catn $_ } }
    Get-ChildItem $env:scripts\ModulesByCxxu\ConstantStrings -r | 
    ForEach-Object { 
        if (($_.ToString() -like "* $pattern * ") -or ( Select-String -Path $_ -Pattern $pattern ) ) 
        { 
            Write-Output $_; 
            PrintBorder
            # catn 是自定义函数模仿linux cat -n 效果.
            catn $_ ; 
            # 如果使用break,则指打印第一个满足条件的文件
            # break ;
            PrintBorder

        } 
    }
}
function aliasEdit
{
    c $aliasesConfig
}
function searchDirectories
{
    <#     
    .synopsis
    从当前目录开始递归查找具有指定名称的目录
    .Example 
    searchDirectories 'css' 
    searchDirectories -dirFrom_optional ./dir1/  -pattern css 
     #>
    param(
        $pattern,
        $dirFrom_optional = './',
        $isWildcard_optional = 'y',
        $maxDepth = 3
    )
    printWorkingDir $dirFrom_optional
    Write-Output "max-depth=$maxDepth; if you want to search deeper directory, please modify the maxDepth as you want(0 will be equivalent 10)"
    # $wildPattern="* $pattern * "
    # Write-Output 'searching...'
    if ($isWildcard_optional -eq 'y')
    {
        $pattern = "* $pattern * "

    }
    if ($maxDepth -eq 0)
    {
        $maxDepth = 10
    }
    Get-ChildItem -Path $Dir -Directory -Recurse -Filter $pattern -FollowSymlink -Depth $maxDepth | Select-Object name, FullName 

    PrintBorder --
  
}

# test the searchString
function searchStrings
{
    <# 
    .Example
    searchStrings replace 
    searchStrings zsh -m 
    #>
    param(
        $pattern ,
        $mode = 's' 
    )
    Write-Output "options:`s` is for singleline string search; `n -m is for multilines search!"
    Write-Output "the default search mode is 's' "
    $pathPrefix = "$env:psModulesByCxxu\LongOrNewStrings\"

    # Write-Output $pathPrefix
    if ($mode -eq 's' -or $mode -eq '-s')
    {
        Write-Output 'you are search in singleLine strings'
        # Select-String -Path $env:psModulesByCxxu\LongOrNewStrings\singleLineStrings -Pattern $pattern
        $pathSingle = $pathPrefix + 'singleLineStrings'
        Write-Output "😎search strings in the $pathSingle"
        Select-String -Path $pathSingle -Pattern $pattern
    }
    else
    {

        Write-Output 'you are search in MultiLine strings'
        
        # -m (multiLines mode)!!!
        $pathMulti = $pathPrefix + 'multiLines\'
        Write-Output "😎😎search strings in the $pathMulti"
        
        Select-String -Path $($pathMulti + '*') -Pattern $pattern
        $patternLs = "*$pattern*" 
        Get-ChildItem $pathMulti "$patternLs" | Get-Content 
    
    }
    
}

function gctm
{
    param([String]$CommentStr)
    git commit -m $CommentStr
}
function gitAdd
{
    param(
        $item = '.'
    )
    git add $item
    PrintBorder
    gits
}
function lsn
{
    Get-ChildItem -Name
}
function yd
{
    y dev
}
function yt
{
    y test
}
# function y
function openLink
{
    param (
        $linkMark
    )
    msedge $linkMark
}

function gitS
{
    git status
}
function e
{
    exit
}
function ipa
{
    param (
        
    )
    ipconfig -all
}
function rootT
{
    param (
        
    )
    ssh $env:Troot
}
# testing.
function mkdirSafeCd
{
    param(
        $DirectoryName

    )
    if ( Test-Path $DirectoryName)
    {
        Write-Output "directory already exist, now Set-Location to the directory:$DirectoryName"
        Set-Location $DirectoryName
    }
    else
    {
        New-Item -ItemType Directory $DirectoryName
        Set-Location $DirectoryName
    }
}
function EggNew
{
    param (
        $projectDir = "new_egg_$(Get-Date)"
    )
    # 检查目录存在性,以及判空(judgePath/judgeFile/judgeDir)
    if ( Test-Path $projectDir)
    {
        Write-Output "directory already exist, now Set-Location to the directory:$projectDir"
        $itemList = Get-ChildItem $projectDir
        if ($itemList.count -eq 0)
        {
            Set-Location $projectDir
        }
        else
        {
            Write-Output "this folder:$projectDir is not empty, it is adviced to initial eggProject with a new(or empty) folder.returning..."
            return
        }
    }
    else
    {
        New-Item -ItemType Directory $projectDir
        Set-Location $projectDir
    }
    # mkdir $projectDir
    # Set-Location $projectDir
    Write-Output "@😎😎😎creating new egg project in $pwd"
    yarnNode create egg --type=simple
    yarnNode install
    Get-ChildItem
}

function ipv
{
    param (
        $ipGen = 4
    )
    #    ipa | ForEach-Object { Write-Output $_ } | Select-String "(lan.*wi.*fi) | ethernet | v$ipGen"
    ipa | Select-String "(lan.*wi.*fi) | ethernet | v$ipGen"
}
function restartExplorer
{
    param (
        
    )
    # for powershell ,to restart the explorer just need a cmdlet(more simple than command in cmd like bellow.)
    Stop-Process -Name explorer 
    # taskkill /f /im explorer.exe 
    # Start-Process explorer.exe
}
function gitNoRepeatValidate
{
    # for oldVersion git in windows
    param (
        $time = 100000
    )
    git config --global credential.helper "cache --timeout $time"
}
function backupEnvs_regeditPrintPath
{
    param (
        
    )
    Write-Output $env:envRegedit "`\ncontent has been set to clipborad😊"
    Set-Clipboard $env:envRegedit
    regedit.exe
}
function pipUpdateIntegration
{
    param (
        
    )
    python -m pip install --upgrade pip
}
function pwsh_upgrade
{
    Invoke-Expression "& { $(Invoke-RestMethod https://aka.ms/install-powershell.ps1) } -UseMSI"
}
function pwshnologo
{
    param (
        
    )
    pwsh -nologo
}
function sudo_pwsh
{
    sudo pwsh -nologo
}
# testing...
function c
{
    param(
        $dirName = '.'
    )
    code $dirName 
    # --proxy-pac-url=http://127.0.0.1:1083/proxy.pac
}
function code_proxy
{
    $dirName = '.'
    code $dirName --proxy-pac-url=http://127.0.0.1:1083/proxy.pac
}
# function cdb{
#     cd -
# }
function cdp
{
    Set-Location ..
}
function rmFV
{
    param(
        # Parameter help description
        #    [ParameterType]
        [Parameter(Mandatory, HelpMessage = 'input the object you want to delete by -Force')]
        $dirName
    )
    Remove-Item $dirName -Force -Verbose

}

function predictNo
{
    param (
        
    )
    Set-PSReadLineOption -PredictionSource None
}
# function predict {
#     Set-PSReadLineOption -PredictionSource History # 设置预测文本来源为历史记A
# }
function tree_pwsh
{
    # Closure function
    <# 
    .synopsis
    本函数支持遍历目录和文件
    也可以选择仅遍历目录而部列出文件
    通过缩进来表示嵌套层次关系
    支持指定最大遍历深度;指定为0时,表示不限制深度
    .example
    recurseClosure -traverseType d -maxDepth 3

    recurseClosure -traverseType a -maxDepth 3 -path D:\repos\scripts\linuxShellScripts\
    排除关键字示例(可以修改-eq为-like / -match 来支持通配符或正则表达式)
    recurseTree -exclude "node_modules"  -maxDepth 0 |sls -Pattern "Rand.*"
    #>

    # 参数置顶原则
    param(
        $traverseType = '',
        $path = './',
        $maxDepth = '2',
        $exclude = ''
    )
    
    $depth = 1
    $times = 0
    function listRecurse
    {
        <# 遍历所有子目录 #>
        param(
            $traverseType = '',
            $path = ''
        )
        # Write-Output "`tpath=$path"
        if ($traverseType -eq 'd')
        {
            $lst = (Get-ChildItem -Directory $path)
        }
        else
        {
            $lst = (Get-ChildItem $path)

        }

        # 子目录数目len
        $len = $lst.Length
        $times++;

        #每一层处理都是都是一重循环O(n)
    
        # 遍历子目录
        <# 注意需要添加对文件的判断,否则在对文件调用本函数的时候,会陷入死循环(无法进入深层目录) #>
        $lst | ForEach-Object {
            $len--;
            # Write-Output "`t`t remain times :len=$len";
            if ($_.BaseName -like $exclude)
            {
                # pass it
            }
            else
            {

                # 打印每个子目录及其深度
                # 无树干的前缀字符串(简洁版)
                # $indent = "`t" * ($depth - 1)
                # 如果想要画出所有的枝干,需要在intend这段字符串做改进(不单单是合适数量的制表符.)
                # 总之,每一行可能有多个`|`:第n层的条目,需要有n条树干线(而且,同一行的内容只能够一次性打印完,)
                # 所以,我们应该计算并安排好每一行的前缀字符串(树干线)

                # 带树干的字符串:│ ├ ─  └ ─ |
                $indent_tree = "│`t" * ($depth - 1) + '│'
                # 打印路径
                $pathNameRelative = $_.baseName
                Write-Output "$indent_tree`──($depth)$($pathNameRelative)"

                if ((Get-Item $_) -is [system.io.directoryinfo] )
                {
                    # 打印树干
                    # 其实还要考虑要求打印的深度的截至
                    if (@(Get-ChildItem $_).Count -gt 0  )
                    {
                        # Write-Output @(Get-ChildItem $_).Count
                        # $branch = '|' + "`t" * ($depth - 1) + '  \____.'
                        $branch = $indent_tree + '  ├────'
                        # $branch = $indent_tree 

                        if ($depth -eq $maxDepth)

                        {
                            <# Action to perform if the condition is true #>
                            $branch += '......'
                        }
                        $branch
                    }

                    $depth++
                    # write
                    # 对子目录继续深挖,(做相同的调用)
                    if ($depth -le $maxDepth -or $maxDepth -eq 0)
                    {
                        listRecurse -path $_.FullName -traverseType $traverseType
                    }
                    $depth--
                }
                # Write-Output "$depth"
                # Start-Sleep -Milliseconds 1000
            }
        } 
    }   

    listRecurse -traverseType $traverseType -path $path
    # listRecurse

}


function status { git status }
function time_show
{
    param (
        
    )
    EnvironmentRequireTips;    
    py $env:scripts\pythonscripts\timer.py
}
function tr_py
{
    <# don't place any other statments before the param() #>
    param (
        $dirName = '.\',
        $depth = 1
    )
    EnvironmentRequireTips
    py $env:scripts\pythonScripts\tree_pyScript.py $dirName $depth
    
}
function Operators_Comparison_pwsh
{
    help about_Comparison_Operators
}
function  Operators_Logical_pwsh
{
    help about_Logical_Operators
}
function Operators_all_pwsh
{
    help about_Operators
}
function printWorkingDir
{
    param(
        $path = './'
    )
    Write-Output "`t 📁❤️function working on dir: $((getAbsolutePath $path))..."
    PrintBorder '..'
}
function backupSymbolicLinks
{
    param (
        # $saveToPath = 'c:\users\cxxu\desktop\links'
        $saveToPath = "$env:configs\symbolicLinks"
        # home
        # d_drive
    )
    Write-Output "❤️❤️writing to path:$saveToPath..."
    # $buffer = Get-ChildItem | Sort-Object -Property Name | Select-Object linktype, name, target | Where-Object { $_.Target }  
    Write-Output 'get symbolicks...'
    $buffer = getLinks

    # Write-Output 'check the buffer'
    # Write-Output $buffer
    # Write-Output "creating or reseting the file $saveTopath ..."
    ''> $saveToPath  
    
    PrintBorder '<<'
      
    # Write-Output '😎:setting the row content of the target file(with header lines.)...'
    # Write-Output 'removing headers...'
    # (Get-Content $saveToPath | Select-Object -Skip 3 ) | Out-File -Verbose -Force $saveToPath
    # Write-Output 'removing top three line (header lines)...'
    # $buffer = $buffer | Format-Table -HideTableHeaders
    $buffer>$saveToPath
    
    Write-Output 'display and check the contents of backed file...'
    Get-Content $saveToPath
    PrintBorder '>>'
    Write-Output "itemsCount: $($buffer.count)"

}
function getLinks
{
    <# 
    .example
    getLinks 'C:\Program Files\',d:\,c:\users
    PS D:\repos\scripts> getLinks 'C:\Program Files\',d:\,c:\users
    # comments:😁😁detecting the path:@ D:\repos\scripts...

    Junction Microsoft VS Code D:\Program Files\Microsoft VS Code
    # comments:😁😁detecting the path:@ D:\repos\scripts...
    Junction books             d:\org\booksRepository
    Junction dp                D:\Program Files\
    Junction dp86              D:\Program Files (x86)\
    Junction org               d:\OneDrive - pop.zjgsu.edu.cn\
    #>
    param (
        # 数组
        $checkPath_opt = @($home, 'D:\')
    )
    # Write-Output "......# comments:😁😁detecting the path:$(Get-Location)..."
    # $buffer = Get-ChildItem | Sort-Object -Property Name | Select-Object linktype, name, target | Where-Object { $_.Target }  

    $buffer = $checkPath_opt.ForEach(
        {
            Write-Output "# comments:😁😁detecting the path:@ $(Get-Location)...";
            Get-ChildItem $_ | Sort-Object -Property Name | Select-Object linktype, name, target | Where-Object { $_.Target }  ; 
            # PrintBorder '#' 
        }
    )
    $buffer = $buffer | Format-Table -HideTableHeaders
    # Write-Output $buffer
    return $buffer
    
}
function showLinks
{
    $buffer = getLinks
    Write-Output $buffer
    PrintBorder '>>'
    Write-Output "itemsCount: $($buffer.count)"
    
}
function commitAmend
{
    [CmdletBinding()]
    param (
        
    )
    git commit --amend
}
function checkGitReports
{
    param (
        
    )
    py $env:scripts\pythonScripts\checkGitReports.py
}
#(please note that the function name can't not have a same name with a certain Alias).
function lsf { Get-ChildItem -Force }
function ls_sudo { sudo ls }

<# start comman software by name #>
function wmqtt
{
    java -jar $env:wmqtt/wmqttSample.jar
}
# function antlr4
# {
#     param(
#         # [String[]]$params
#         $p1 = '',
#         $p2 = '',
#         $p3 = ''
#     )
#     # java -jar D:\antlr4.jar $params

#     java -jar D:\antlr4.jar $p1 $p2 $p3
# }
#  set proxy for pwsh
function set_proxy_variable
{
   
    <# 
    .synopsis
    打开或者关闭gitconfig的全局配置;操作完成后查看配置文件
    .example
     git_proxy_set -switch_opt off
    .example
     git_proxy_set -switch_opt on
    .example
    git_proxy_set -switch_opt on -port_opt 1099
    #>
    param(
        $switch_opt = 'on',
        $port_opt = '10801',
        $localhost_opt = 'http://127.0.0.1'

    )
    $localhost = $localhost_opt
    $socket = "$localhost`:$port_opt"
    
    if ($switch_opt -eq 'on')
    {
        
        Set-Item Env:http_proxy $socket  # 代理地址
        Set-Item Env:https_proxy $socket # 代理地址
        Invoke-WebRequest www.google.com | bat
    }
    elseif ($switch_opt -eq 'off')
    {   
        Remove-Item Env:http_proxy
        Remove-Item Env:https_proxy
    }
    
}
function btm_cxxu
{
    btm --color nord-light
}

<# functions with parameters #>
function path_counter
{
    $env:Path -split ';' | catn
}
function envInPath
{
    <# 
    .synopsis
    check if a value is contain in the Path variable value.
     #>
    param (
        $pattern = '*'
    )

    Write-Output '😎😎😎within Path:'
    if ($pattern -eq '*')
    {
        $env:path -split ';'
        return
    }
    $env:path -split ';' | Select-String -Pattern $pattern
}

function envNoPath
{
    param (
        [string]$pattern = '*'
    )

    Write-Output '😊😊😊without Path'
    $envs = Get-ChildItem env:* -Exclude Path
    $envs>envs
    $envs = Get-Content envs
    # if ($pattern -eq '*')
    # {
    #     printenv | Select-String 'path=' -NotMatch
    #     return
    # }
    Remove-Item envs
    return $envs | Select-String 'path=' -NotMatch | Select-String -Pattern $pattern
}
function envAll
{
    # param (
    #     $pattern = '*'
    # )
    # envNoPath $pattern
    # envInPath $pattern
    Get-ChildItem env:* | Format-Table -Wrap autosize 
}

function envSearch
{
    param (
        $pattern = '*',
        $isContainPath = 'all'
    )
    if ($isContainPath -eq 'p')
    {
        Write-Output '...within path.....' 
        envInPath $pattern
    }
    elseIf ($isContainPath -eq 'n' -or $isContentPath -eq 'np')
    {
        Write-Output "...within nonPath.....`\n"
        envNoPath $pattern
    }
    else
    {
        Write-Output '... env all .....'
        envAll $pattern
    }
}

function t
{
    tree /f
}
function mvs
{
    param (
        $item
    )
    
}
function recycleItem
{
    param(
        $Item
    )
    $recycleBin = "$env:desktop\recycleBin"
    if ( ! (Test-Path $recycleBin))
    {
        mkdir $recycleBin
    }
    Move-Item -Verbose $item $recycleBin
}
function mvv
{
    # cd D:\repos\learnPwsh\ModulesByCxxu\testMvv\inner
    Move-Item $args[0] $args[1] -Verbose
}

function renameScreenPic
{
    param (
        $bakDir = $env:pictures
    )
    py $env:scripts\pythonScripts\renameFiles.py
    Copy-Item $env:screenPic\* $bakDir
}
function updateTodo
{
    Set-Location $env:repos/todo
    git add .
    git commit -m "date:$(Get-Date)"
    git push origin main
    Set-Location -
}
function blogs
{
    param(
        $isCode
    )
    Set-Location $env:repos/blogs
    if ($isCode.length -gt 0)
    {
        c
    }
    
}

function testIfElse
{
    <# 
    
    .EXAMPLE
     'Server1', 'Server2' | Get-MrAutoStoppedService
    #>
    [CmdletBinding()]
    param (
        [Parameter()]
        [int]
        $n
    )
    Write-Output 'testing...'
    Write-Output $n
    if ($n -gt 5)
    {
        Write-Output 'bigger than 5'
    }
    else
    {
        Write-Output 'smaller than 5'
    }
}
